package com.lwj.exception;

import com.lwj.entity.RestEntity;
import com.lwj.mapper.AuditInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class ExceptionHandlerAdvice  {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public @ResponseBody
    RestEntity businessException(BusinessException ex) {
        logger.error(ex.getMessage());
        return RestEntity.error(ex.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR.value());
    }
    @ExceptionHandler(NoPermissionException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public @ResponseBody
    RestEntity noPermission(NoPermissionException ex) {
        logger.error(ex.getMessage());
        return RestEntity.error(ex.getMessage(),HttpStatus.UNAUTHORIZED.value());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public @ResponseBody
    RestEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder errorMesssage = new StringBuilder("格式有误: \n");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage.append(fieldError.getDefaultMessage()).append("\n");
        }
        return RestEntity.error(errorMesssage.toString());
    }
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public @ResponseBody
    RestEntity lastDefence(Exception ex) {
        ex.printStackTrace();
        logger.error("系统繁忙",ex);
        return RestEntity.error("系统繁忙");
    }
}
